package promote.brozen.algorithm.tree.binary;

import promote.brozen.algorithm.tree.TreeNode;

import java.util.ArrayList;

/**
 * @author Brozen
 * @date 2019/12/19 8:21 AM
 */
public class BinaryTreeNode<K, S extends BinaryTreeNode<K, S>> extends TreeNode<K, S> {

    public BinaryTreeNode(K key) {
        super(key);
        children = new ArrayList<>(2);
        children.add(null);
        children.add(null);
    }

    public S getLeftChild() {
        return children.get(0);
    }

    public void setLeftChild(S left) {
        children.set(0, left);
        if (left != null) {
            left.setParent(this);
        }
    }

    public S getRightChild() {
        return children.get(1);
    }

    public void setRightChild(S right) {
        children.set(1, right);
        if (right != null) {
            right.setParent(this);
        }
    }

    @Override
    public BinaryTreeNode<K, S> getParent() {
        return (BinaryTreeNode<K, S>) super.getParent();
    }

    public boolean isLeftChildOfParent() {
        return getParent() != null && getParent().getLeftChild() == this;
    }

    public boolean isRightChildOfParent() {
        return getParent() != null && getParent().getRightChild() == this;
    }

    public boolean isLeaf() {
        return getLeftChild() == null && getRightChild() == null;
    }

    @Override
    public String toString() {
        S left = getLeftChild();
        S right = getRightChild();
        return "BinaryTreeNode[" + key
                + "] Left[" + (left == null ? null : left.getKey())
                + "] Right[" + (right == null ? null : right.getKey()) + "]";
    }
}
